<template>
  <div class="notification-detail-page">
    <!-- 面包屑导航 -->
    <div
      class="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700"
    >
      <div class="container mx-auto px-4 py-2">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/user' }"
            >个人中心</el-breadcrumb-item
          >
          <el-breadcrumb-item :to="{ path: '/user/messages' }"
            >消息中心</el-breadcrumb-item
          >
          <el-breadcrumb-item>通知详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="max-w-3xl mx-auto">
        <div class="bg-white dark:bg-gray-900 rounded-xl shadow-sm p-8">
          <!-- 通知标题 -->
          <div class="flex items-start justify-between mb-6">
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              {{ notification.title }}
            </h1>
            <el-tag
              :type="getNotificationTagType(notification.type)"
              size="large"
            >
              {{ getNotificationTypeLabel(notification.type) }}
            </el-tag>
          </div>

          <!-- 通知时间和状态 -->
          <div
            class="flex items-center space-x-4 text-gray-500 dark:text-gray-400 mb-8"
          >
            <span>{{ formatDetailTime(notification.time) }}</span>
            <span>|</span>
            <span>{{ notification.isRead ? "已读" : "未读" }}</span>
          </div>

          <!-- 通知内容 -->
          <div class="prose prose-lg dark:prose-invert max-w-none mb-8">
            <div v-html="notification.content"></div>
          </div>

          <!-- 附加信息 -->
          <div
            v-if="notification.attachments?.length"
            class="border-t border-gray-100 dark:border-gray-800 pt-6"
          >
            <h3 class="text-lg font-medium mb-4">附件信息</h3>
            <div class="space-y-3">
              <div
                v-for="attachment in notification.attachments"
                :key="attachment.id"
                class="flex items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg"
              >
                <el-icon class="text-gray-400 mr-3"><Document /></el-icon>
                <span class="flex-1">{{ attachment.name }}</span>
                <el-button
                  type="primary"
                  link
                  @click="downloadAttachment(attachment)"
                >
                  下载
                </el-button>
              </div>
            </div>
          </div>

          <!-- 相关链接 -->
          <div
            v-if="notification.links?.length"
            class="border-t border-gray-100 dark:border-gray-800 pt-6"
          >
            <h3 class="text-lg font-medium mb-4">相关链接</h3>
            <div class="space-y-2">
              <div
                v-for="link in notification.links"
                :key="link.id"
                class="flex items-center text-primary-500 hover:text-primary-600"
              >
                <el-icon class="mr-2"><Link /></el-icon>
                <a :href="link.url" target="_blank">{{ link.title }}</a>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div
            class="flex items-center justify-between mt-8 pt-6 border-t border-gray-100 dark:border-gray-800"
          >
            <el-button @click="router.back()">返回</el-button>
            <div class="space-x-4">
              <el-button
                type="primary"
                @click="handleReply"
                v-if="notification.canReply"
              >
                回复
              </el-button>
              <el-button type="danger" @click="handleDelete"> 删除 </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Document, Link } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import axios from "@/api/axios";

const route = useRoute();
const router = useRouter();

// 通知详情数据
const notification = ref({
  id: "",
  type: "",
  title: "",
  content: "",
  time: "",
  isRead: false,
  canReply: false,
  attachments: [],
  links: [],
});

// 加载状态
const loading = ref(false);

// 模拟数据（备用）
const mockNotification = {
  id: 1,
  type: "system",
  title: "系统升级通知",
  content: `
    <p>尊敬的用户：</p>
    <p>为了给您提供更好的服务体验，我们计划于2024年3月20日凌晨2:00-4:00进行系统升级维护。在此期间，部分功能可能无法正常使用。</p>
    <p>升级内容：</p>
    <ul>
      <li>优化系统性能</li>
      <li>提升安全性</li>
      <li>新增部分功能</li>
    </ul>
    <p>给您带来的不便，敬请谅解。</p>
  `,
  time: "2024-03-15 10:00:00",
  isRead: false,
  canReply: false,
  attachments: [
    {
      id: 1,
      name: "系统升级说明.pdf",
      url: "/files/upgrade-guide.pdf",
    },
  ],
  links: [
    {
      id: 1,
      title: "查看升级详情",
      url: "/help/upgrade-guide",
    },
  ],
};

// 获取通知类型标签
const getNotificationTypeLabel = (type) => {
  const typeMap = {
    system: "系统通知",
    maintenance: "维护通知",
    update: "更新通知",
    security: "安全通知",
  };
  return typeMap[type] || type;
};

// 获取通知类型样式
const getNotificationTagType = (type) => {
  const typeMap = {
    system: "info",
    maintenance: "warning",
    update: "success",
    security: "danger",
  };
  return typeMap[type] || "info";
};

// 格式化时间
const formatDetailTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 下载附件
const downloadAttachment = async (attachment) => {
  try {
    // 实际的附件下载API调用
    const response = await axios.get(`/user/notifications/attachments/${attachment.id}`, {
      responseType: 'blob'
    });
    
    // 创建blob链接并触发下载
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', attachment.name);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage.success(`开始下载：${attachment.name}`);
  } catch (error) {
    console.error("下载附件失败:", error);
    ElMessage.error("下载附件失败，请稍后重试");
  }
};

// 处理回复
const handleReply = async () => {
  // TODO: 实现回复功能
  ElMessage.info("回复功能正在开发中");
};

// 处理删除
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm("确定要删除这条通知吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    try {
      // 调用删除API
      await axios.delete(`/user/notifications/${notification.value.id}`);
      ElMessage.success("删除成功");
      router.push("/user/messages");
    } catch (error) {
      console.error("删除通知失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  } catch {
    // 用户取消操作
  }
};

// 标记通知为已读
const markAsRead = async (notificationId) => {
  try {
    await axios.put(`/user/notifications/${notificationId}/read`);
  } catch (error) {
    console.error("标记通知为已读失败:", error);
  }
};

// 获取通知详情
const getNotificationDetail = async () => {
  loading.value = true;
  try {
    const notificationId = route.query.id;
    if (!notificationId) {
      ElMessage.error("通知ID不能为空");
      router.push("/user/messages");
      return;
    }

    // 调用获取详情API
    try {
      const { data } = await axios.get(`/user/notifications/${notificationId}`);
      notification.value = {
        ...data,
        // 格式化时间
        time: data.time || data.createTime || data.create_time || new Date()
      };
      
      // 标记为已读
      if (!notification.value.isRead) {
        await markAsRead(notificationId);
        notification.value.isRead = true;
      }
    } catch (error) {
      console.error("获取通知详情失败:", error);
      // 使用模拟数据
      notification.value = {
        ...mockNotification,
        id: notificationId
      };
      ElMessage.warning("使用测试数据显示");
    }
  } catch (error) {
    console.error("获取通知详情失败:", error);
    ElMessage.error("获取通知详情失败");
    router.push("/user/messages");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getNotificationDetail();
});
</script>

<style lang="scss" scoped>
.notification-detail-page {
  .prose {
    ul {
      @apply list-disc pl-6 mb-4;
      li {
        @apply mb-2;
      }
    }
  }
}
</style>
